<?php defined('SYSPATH') or die('No direct script access.');

/*
*
*
*
*/

class Controller_Purchase extends Controller_Admin
{

    /**
     *手动新建采购单

     */
    public function before()
    {
        try{
            ACL::Required('purchase_add_for_supplier');
        }catch(HTTP_Exception_403 $e){
            Message::error('sorry，你没有权限进这个目录');
            $this->request->redirect(URL::base(TRUE));
        }
        include_once(MODPATH.'/common/logs.php');
        parent::before();
    }

    /**
     * 描述:创建预约单界面
     * 作者:kelvin
     */
    public function action_addView()
    {
        $this->title = __('根据供应商新建预约单');
        $warehouses = Kohana::$config->load('warehouse')->warehouses;
        $view = View::factory('purchase/addView');
        $view->set('types', Kohana::$config->load('ratetypes')->get('types'));
        $view->set('tran', Kohana::$config->load('ratetypes')->get('tran_way'));
        $view->set('user',User::active_user());
        //添加国内仓库 2016-02-15
        $view->set('enterprise_dominant',Kohana::$config->load('enterprise_dominant')->as_array());
        $view->set('warehouses', $warehouses);
        $this->response->body($view);
    }
    /**
     * 描述:根据sku创建预约单界面
     * 作者:kelvin
     */
    public function action_skuaddView()
    {
        $this->title = __('根据SKU新建预约单');
        $warehouses = Kohana::$config->load('warehouse')->warehouses;
        $view = View::factory('purchase/skuaddView');
        $view->set('types', Kohana::$config->load('ratetypes')->get('types'));
        $view->set('tran', Kohana::$config->load('ratetypes')->get('tran_way'));
        $view->set('user',User::active_user());
        //添加国内仓库 2016-02-15
        $view->set('enterprise_dominant',Kohana::$config->load('enterprise_dominant')->as_array());
        $view->set('warehouses', $warehouses);
        $this->response->body($view);
    }
    /**
     * 描述:获取用户列表
     * 作者:kelvin
     */
    public function action_get_users()
    {
        if(isset($_GET['term'])){
            $results = array();
            $name = trim($_GET['term']);
            $user = DB::query(Database::SELECT, "SELECT `id`,`nick` FROM `users` WHERE nick like '%{$name}%' limit 15")->execute('newerp')->as_array();
//            $user = DB::query(Database::SELECT, "SELECT `id`,`nick` FROM `users` WHERE nick like '%{$_GET['term']}%' ")->compile('newerp');
            if($user){
                foreach($user as $supplier){
                    $id        = $supplier['id'];
                    $str       = trim($supplier['nick']);
                    $results[] = array(
                        'id'    => $id,
                        'label' => $str,
                        'name'  => $str
                    );
                }
                echo json_encode($results);
                exit;
            }

        }

    }
    /*
    *创建采购单界面
    */
    public function action_select_sku()
    {

        $pay = DB::select('id','payment')
            ->from('erp_provider')
            ->where(DB::expr('trim(replace(replace(vProviderName,"\n",""),"\r",""))'),'=',trim($_POST['supplier_id']))
            ->where('state','=',2)
            ->execute('readonlyerp')
            ->current();

        $provider_info = DB::select('price','iproviderID','nuit','ID','delivery')
            ->from('erp_providerproducts')
            ->where(DB::expr('trim(replace(replace(iproductID,"\n",""),"\r",""))'),'=',trim($_POST['sku']))
            ->where('iproviderID','=',trim($pay['id']))
            ->execute('readonlyerp')
            ->current();
        if(!empty($provider_info)){
            $provider_info['delivery'] = date('Y-m-d',(time()+$provider_info['delivery']*24*3600));
        }

        $product_info = DB::select('products_sku','products_name_cn','products_place','products_values')
            ->from('erp_products_data')
            ->where(DB::expr('trim(products_sku)'),'=',trim($_POST['sku']))
            ->execute('readonlyerp')
            ->current();
        if(is_array($product_info)&&is_array($provider_info)&&is_array($pay)){
            $skuinfo = Basic::get_sku_status(array(trim($_POST['sku'])));
            if(isset($skuinfo[strtoupper(trim($_POST['sku']))]['status_string'])){
                $product_info['status'] = $skuinfo[strtoupper(trim($_POST['sku']))]['status_string'];
            }else{
                $product_info['status'] = '未知状态';
            }
            echo json_encode(array_merge($product_info,$provider_info,$pay));
            exit;
        }else{
            echo json_encode(0);
            exit;
        }
    }

    public function action_detail_purchase()
    {
        $purchase_status                 = Config::load('purchase_status');
        $purchaseorder_status            = $purchase_status->purchaseorder;
        $purchaseorder_info              = Purchase::select_purchase_info($_POST['id']);
        $purchaseorder_detail            = Purchase::change_purchase($_POST['id']);
        $purchaseorder_info['money_fee'] = $purchaseorder_info['money']+$purchaseorder_info['transportation_expense'];
        $html                            = "	<table class='table table-bordered ' id='purchase_order'>
                                <tr class='headings'>                                    
                                    <th style='width:6%;'>
                                        采购员
                                    </th>
                                    <th style='width:5%;'>
                                        总金额
                                    </th>
                                    <th style='width:5%;'>
                                        采购金额
                                    </th>
                                    <th style='width:6%;'>
                                        运费
                                    </th>		  
																		<th style='width:6%;'>
                                       	采购单号
                                    </th>
                                    <th style='width:5%;'>
                                        状态
                                    </th>
				    												<th style='width:5%;'>
                                        创建时间
                                    </th>
																		<th style='width:5%;'>
                                        打印时间
                                    </th>
																		<th>
																				支付方式
																		</th>
			  
                                </tr>
																<tr>
                                    <td style='width:6%;'>
																		".$purchaseorder_info['name']."
                                    </td>
                                      <td style='width:5%;'>
																		".number_format($purchaseorder_info['money_fee'],2)."
                                    </td>
                                    <td style='width:5%;'>
																		".number_format($purchaseorder_info['money'],2)."
                                    </td>
                                    <td style='width:6%;'>
																		".number_format($purchaseorder_info['transportation_expense'],2)."		
                                    </td>		    			
																		<td style='width:6%;'>
																		".$purchaseorder_info['id']."
                                    </td>
                                    <td style='width:5%;'>
																		".$purchaseorder_status[$purchaseorder_info['status']]."
                                    </td>
				    												<td style='width:5%;'>
																		".$purchaseorder_info['purchaseorder_date']."
                                    </td>
				    												<td style='width:5%;'>
																		".$purchaseorder_info['purchase_time']."
                                    </td>
				    												<td style='width:5%;'>
																		".$purchaseorder_info['pay_way']."
                                    </td>																				
																															
																</tr>";
        $html .= "
                                <tr class='headings'>                                    
                                    <th style='width:6%;'>
                                        采购明细单
                                    </th>
                                    <th style='width:5%;'>
                                        sku
                                    </th>
                                    <th style='width:5%;'>
                                        sku名称
                                    </th>
                                    <th style='width:6%;'>
                                        单价
                                    </th>		  
																		<th style='width:6%;'>
                                       	数量
                                    </th>
                                    <th style='width:5%;'>
                                        金额
                                    </th>
				    												<th style='width:5%;'>
                                        计税
                                    </th>
																		<th style='width:5%;'>
                                        税率
                                    </th>
																		<th>
																				交货日期
																		</th>
			  
                                </tr>";
        foreach($purchaseorder_detail as $key => $purchaseorder_details){
            switch($purchaseorder_details['tax_way']){
                case 0:
                    $purchaseorder_details['tax_way'] = "不计税";
                    break;
                case -1:
                    $purchaseorder_details['tax_way'] = "内含税";
                    break;
                case 1:
                    $purchaseorder_details['tax_way'] = "外加税";
                    break;
                default:
                    $purchaseorder_details['tax_way'] = "不计税";;
            }
            $html .= "<tr>
                                    <td style='width:6%;'>
																		".$purchaseorder_details['id']."
                                    </td>
                                      <td style='width:5%;'>
																		".$purchaseorder_details['sku']."
                                    </td>
                                    <td style='width:5%;'>
																		".$purchaseorder_details['sku_name']."
                                    </td>
                                    <td style='width:6%;'>
																		".$purchaseorder_details['single_price']."		
                                    </td>		    			
																		<td style='width:6%;'>
																		".$purchaseorder_details['quantity']."
                                    </td>
                                    <td style='width:5%;'>
																		".number_format($purchaseorder_details['money'],2)."
                                    </td>
				    												<td style='width:5%;'>
																		".$purchaseorder_details['tax_way']."
                                    </td>
				    												<td style='width:5%;'>
																		".$purchaseorder_details['tax_rate']."
                                    </td>
				    												<td style='width:5%;'>
																		".$purchaseorder_details['arrive_date']."
                                    </td>																				
																															
																</tr>";
        }
        $html .= "</table>";
        echo json_encode($html);
        exit;
    }

    public function action_addnew()
    {
        $this->title    = __('新建采购单');
        $purchase_array = Service_purchaseadd::get_purchaseorder_num();
        $view           = View::factory('addnew')
            ->set('purchase_array',$purchase_array);

        /**
         * 从数据库获取付款方式
         * 存在erp_database数据表erp_pay_type,标示付款方式
         * @time 20140813
         */
        $pay_ways = Service_warning::get_pay_ways();
        $view->set('pay_ways',$pay_ways);

        $this->response->body($view);
    }

    /**
     * 查询建议价格
     */
    public function action_selectadvice()
    {
        $sku          = trim($this->request->post('sku'));
        $sql_product  = "SELECT `products_values`
					FROM `erp_products_data`
					WHERE `products_sku`='".$sku."'";
        $price_advice = DB::query(Database::SELECT,$sql_product)
            ->execute('readonlyerp')
            ->get('products_values');
        echo json_encode($price_advice);
        exit;
    }

    /**
     * 查询供应商信息
     */
    public function action_selectsupplier()
    {
        $sku           = trim($this->request->post('sku'));
        $sql_supplier  = "SELECT `price`,`iproviderID`,`nuit`,`ID`,`delivery` FROM `erp_providerproducts` WHERE `iproductID` = '".$sku."'";
        $supplier_info = DB::query(Database::SELECT,$sql_supplier)
            ->execute('readonlyerp')
            ->as_array();
        $sql_product   = "SELECT `products_name_cn`
										FROM `erp_products_data` 
										WHERE `products_sku`='".$sku."'";
        $sku_name      = DB::query(Database::SELECT,$sql_product)
            ->execute('readonlyerp')
            ->get('products_name_cn');
        foreach($supplier_info as $key_info){
            $sql_supplier_info = "SELECT `vProviderName`,`payment` FROM `erp_provider` WHERE state =2 AND id =".$key_info['iproviderID'];
            $info              = DB::query(Database::SELECT,$sql_supplier_info)
                ->execute('readonlyerp')
                ->current();
            $data_supplier[]   = $sku;
            $data_supplier[]   = $info['vProviderName'];
            $data_supplier[]   = $key_info['price'];

            if(isset($info['payment'])){
                $pay_way_id = Purchase::get_pay_way(array('type' => $info['payment']));
                if(isset($pay_way_id[0]['id'])){
                    $pay_way_id = $pay_way_id[0]['id'];
                }
            }else{
                $pay_way_id = 0;
            }
            //			$data_supplier[]=$info['payment'];
            $data_supplier[]      = $pay_way_id;
            $data_supplier[]      = $key_info['iproviderID'];
            $data_supplier[]      = $key_info['ID'];
            $data_supplier[]      = $sku;
            $data_supplier[]      = $sku_name;
            $data_supplier[]      = $key_info['nuit'];
            $key_info['delivery'] = date('Y-m-d',(time()+$key_info['delivery']*24*3600));
            $data_supplier[]      = $key_info['delivery'];
        }
        echo json_encode($data_supplier);
        exit;
    }

    /**
     *
     */
    public function action_addpurchase()
    {
        $arrChannel    = json_decode($_POST['json'],TRUE);
        $purchaseorder = new Service_purchaseadd();
        for($i = 0;$i<count($arrChannel);$i++){
            if($i==0){
                //$arrChannel[$i]['pay_way'] = Purchase::change_status($arrChannel[$i]['pay_way']);
                $arrChannel[$i]['pay_way']    = $arrChannel[$i]['pay_way'];
                $arrChannel[$i]['createtype'] = 1;
                $flag                         = $purchaseorder->add_purchaseorder($arrChannel[$i]);
            }else{
                if($arrChannel[$i]['tax_way']==1||$arrChannel[$i]['tax_way']==-1){
                    $arrChannel[$i]['tax_rate'] = $arrChannel[$i]['tax_rate']/100;
                }else{
                    $arrChannel[$i]['tax_rate'] = 0;
                }
                $purchaseorder->add_purchaseorder_details($arrChannel[$i]);
            }
        }
        //Message::success('成功创建'.$flag);
        echo json_encode($flag);
        exit;
    }

    /*
    *展示采购详情数据
    */
    public function action_showproduct()
    {
        $purchase        = Config::load('purchase_status');
        $purchase_status = $purchase->purchaseorder_details;
        $product_info    = Purchase::select_product($_GET['p_id']);
        foreach($product_info AS $key => &$value){
            $value['status'] = $purchase_status[$value['status']];
        }
        $view    = View::factory('purchase/change')
            ->set('product_info',$product_info)
            ->set('p_id',$_GET['p_id'])
            ->render();
        $jsonarr = array(
            'status' => 'y',
            'info'   => '数据查询成功！',
            'view'   => $view
        );
        echo json_encode($jsonarr);
    }

    /**
     *取消采购单
     */
    public function action_deletepurchase()
    {
        $p_detail_id = $this->request->post('p_detail_id');

        $flag        = Purchase::cancel_purchase($p_detail_id);
        if($flag==100){
            echo json_encode("cancel success");
        }else{
            if($flag==90){
                echo json_encode("flag");
            }else{
                echo json_encode("fail");
            }
        }
        exit;
    }

    public function action_cbCancle() {
        //批量取消呢，首先要看能不能取消，不能取消的记录下来反馈给用户
        //允许修改时判断明细修改后状态
        //取消后采购单上金额和运费的平坦问题
        //取消后采购单的状态问题
        $datas = DB::select()->from('purchaseorder_details')->where('id', 'IN', $_POST['deIds'])->execute('newerp')->as_array('id');
        //$bads =

        foreach($datas as $data) {
            $pu_id = $data['purchaseorder_id'];
            $p_detail_id = $data['id'];

            $un_in  = 0;
            $un_out = 0;
            $un_sql = "SELECT sum(quantity) as num FROM `unqualified_deal_invoices` WHERE `sku`='".$sku."' AND `purchaseorder_id`='".$po_id."'";
            $un     = DB::query(Database::SELECT,$un_sql)
                ->execute('newerp');
            if(!empty($un)){

                $un_in = $un[0]['num'];
            }
            $unout_sql = "SELECT sum(`quantity`)  as num FROM `bad_product_delivery` WHERE `status`=20 AND `purchaseorder_id`='".$po_id."' AND `sku`='".$sku."'";
            $unout     = DB::query(Database::SELECT,$unout_sql)
                ->execute('newerp');
            if(!empty($unout)){
                $un_out = $unout[0]['num'];
            }
            return $un_in-$un_out;



            $bad_stock = inventory::select_bad_product_stock($data['purchaseorder_id'],$data['sku']);

            if($bad_stock==0 AND $data['status']<70 && $data['recieve_quantity']-$data['return_quantity']-$data['ware_quantity']==0)
            {
                $remark=0;
                if($data['status']<40)
                {
                    if($data['recieve_quantity']>0){
                        $remark = 90;

                    }else{
                        $remark = 100;

                    }

                    $sql = "UPDATE `purchaseorder_details` SET `status`='".$remark."' WHERE `id` =".$p_detail_id;
                }
                else
                {
                    $remark = 90;
                    $sql = "UPDATE `purchaseorder_details` SET `status`=90 WHERE `id` =".$p_detail_id;
                }
                DB::query(Database::UPDATE,$sql)->execute('newerp');
                if($remark==100){
                    Settle::change_detail_money($p_detail_id,$data,$remark);//更新采购单以及详情单的数据,取消只修改状态，不能修改数量和金额

                }
            }
        }

        //Settle::change_detail_money($p_detail_id,$data,$remark);//更新采购单以及详情单的数据,取消只修改状态，不能修改数量和金额
        $sql = "SELECT `status`
							FROM `purchaseorder_details`
							WHERE `purchaseorder_id` =".$pu_id;
        $status = DB::query(Database::SELECT,$sql)->execute('newerp')->as_array();
        $flag = 0;$mark = 0;$sign = 0;
        foreach($status as $st)
        {
            if($st['status'] < 70)
            {
                return  $remark;
            }
            if($st['status'] == 90)
            {
                $flag = 1;
            }
            if($st['status'] == 100)
            {
                $mark = 1;
            }
            if($st['status'] == 70)
            {
                $sign = 1;
            }
        }
        if($sign == 1)
        {
            $condition = 70;
        }
        else if($flag == 1)
        {
            $condition = 90;
        }
        else if($mark == 1)
        {
            $condition = 100;
        }
        $sql = "UPDATE `purchaseorders` SET `status`=".$condition." WHERE `id` =".$pu_id;
        DB::query(Database::UPDATE,$sql)->execute('newerp');

        if($remark==100){
            echo json_encode("cancel success");
        }else{
            if($remark==90){
                echo json_encode("flag");
            }else{
                echo json_encode("fail");
            }
        }
    }

    /**
     * 重启sku
     */
    public function action_uncancle()
    {
        $p_detail_id = $this->request->post('p_detail_id');

        $sql    = "SELECT * FROM `purchaseorder_details` WHERE `id`= ".$p_detail_id;
        $data = DB::query(Database::SELECT,$sql)->execute('newerp')->current();

        $d_date = strtotime($data['details_date']);
        $now = strtotime(date('Y-m-d H:i:s'));
        $mid = floor(($now - $d_date)/(60*60*24));
        if($mid>5)
        {
            echo json_encode(0);
            exit;
        }

        DB::update('purchaseorder_details')->set(array('status'=>20))
            ->where('id','=',$p_detail_id)
            ->execute('newerp');

        Settle::change_detail_money($p_detail_id,$data,20);

        DB::update('purchaseorders')->set(array('status'=>20))
            ->where('id','=',$data['purchaseorder_id'])
            ->execute('newerp');

        echo json_encode(1);
        exit;
    }

    /**
     *修改采购单的界面
     */
    public function action_changepurchase()
    {
        //$change_info = $this->request->post('');
        $purchaseorder_id   = $_GET['purchaseorder_id'];
        $sql                = "SELECT * FROM `purchaseorders` WHERE `id` = ".$purchaseorder_id;
        $purchaseorder_info = DB::query(Database::SELECT,$sql)
            ->execute('newerp')
            ->current();

        $purchase                     = Config::load('purchase_status');
        $purchase_status              = $purchase->purchaseorder_details; //采购明细单状态
        $purchaseorder                = $purchase->purchaseorder; //采购单状态
        $purchaseorder_info['status'] = $purchaseorder[$purchaseorder_info['status']];
        $purchaseorder_detail         = Purchase::change_purchase($purchaseorder_id);
        $sum_receive                  = 0;
        foreach($purchaseorder_detail as $key => &$value){
            $value['status'] = $purchase_status[$value['status']];
            $sum_receive += $value['recieve_quantity'];
        }

        if($purchaseorder_info['status']>20||$sum_receive>0){
            echo json_encode(0);
            exit;
        }

        $tax_ways = Service_warning::get_tax_ways();
        //所有的采购单状态
        $payways = DB::select('id','paywayname')->from('payways')
            ->where('status','=',0)->execute('newerp')->as_array('id','paywayname');
        $view     = View::factory('purchase/transform')
            ->set('purchaseorder_detail',$purchaseorder_detail)
            ->set('purchaseorder_info',$purchaseorder_info)
            ->set('tax_ways',$tax_ways)
            ->set('pay_way',$purchaseorder_info['pay_way'])
            ->set('payways',$payways)
            ->render();
        $jsonarr  = array(
            'status' => 'y',
            'info'   => '数据查询成功！',
            'view'   => $view
        );
        echo json_encode($jsonarr);
        //echo json_encode($flag);exit;
    }

    /*
    *修改采购单的方法
    */
    public function action_update_purchase()
    {
        $arrChannel = json_decode($_POST['json'],TRUE);
        for($i = 1;$i<count($arrChannel);$i++){
            if($arrChannel[$i]['tax_way']==0){
                $arrChannel[$i]['tax_rate'] = 0;
            }
            $money                = Settle::settle_detail_purchase($arrChannel[$i]); //$arrChannel[$i]['quantity']*$arrChannel[$i]['single_price'];
            $arrChannel[$i]['id'] = trim(trim(trim($arrChannel[$i]['id']),'n'),'t');

            $update               = DB::update('purchaseorder_details')
                ->set(array(
                    'tax_rate'     => $arrChannel[$i]['tax_rate']/100,
                    'arrive_date'  => $arrChannel[$i]['arrive_date'],
                    'tax_way'      => $arrChannel[$i]['tax_way'],
                    'quantity'     => $arrChannel[$i]['quantity'],
                    'single_price' => $arrChannel[$i]['single_price'],
                    'money'        => $money['money'],
                    'tax_money'    => $money['tax_money'],
                    'no_tax_money' => $money['no_tax_money'],
                ))
                ->where('id','=',$arrChannel[$i]['id'])
                ->execute('newerp');
        }
        $arrChannel[0]['id'] = trim(trim(trim($arrChannel[0]['id']),'n'),'t');
        Settle::settle_purchase($arrChannel[0]);
        //yuqing
        checkpurchaseorder::checkSinglePurchaseOrder($arrChannel[0]['id']);
        //yuqing
        echo json_encode(1);
        exit;
    }

    /**
     * 获取供应商详细信息，和SKU基础资料系统对接的
     * @author zhjx
     */
    public function action_supplierpayway()
    {
        $re_view = array();
        if($this->request->is_ajax() and isset($_POST['supplier_id']) and trim($_POST['supplier_id']))
        {
            /**
             * 联系人信息
             */
            $contacts = Newerpclientapi::getSupplierContacts(trim($_POST['supplier_id']));
            if($contacts)
            {
                $contact_view = View::factory('purchase/suppliercontact');
                $contact_view->set('contacts_info',$contacts);
                $re_view['supplier_contanct'] = $contact_view->render();
            }

            /**
             * 付款方式
             */
            $payways = Supplierbank::get_supplier_payways_by_supplier_id(trim($_POST['supplier_id'])); //var_dump($payways);die;
            if($payways)
            {
                $payways_view = View::factory('purchase/supplierpayway');
                $payways_view->set('pay_ways', $payways);
                $re_view['supplier_payway'] = $payways_view->render();
                $bank_account_view = View::factory('purchase/supplierbankinfo');
                $bank_account_view->set('payaccountinfos',$payways);
                $bank_account_view->set('coins',supplierbank::getCoins_arr());
                $re_view['supplier_paybank'] = $bank_account_view->render();
                $re_view['coinid'] = isset($payways[0]['coinid'])?$payways[0]['coinid']:0;
            }
        }

        echo json_encode($re_view);
        exit;
    }

    /**
     * 获取供应商信息,模糊查询,和SKU基础资料系统对接的
     * @author zhjx
     */
    public function action_get_supplier()
    {
        $results = array();
        if(isset($_GET['term'])){
//            $limit     = 15;
//            if(isset($_GET['type'])
//                and $_GET['type'] == 'id')
//            {
//                $condtion = array('id' => ' LIKE "%'.trim($_GET['term']).'%"');
//            }
//            else
//            {
//                $condtion = array('name' => ' LIKE "%'.trim($_GET['term']).'%"');
//            }
            $suppliers = Newerpclientapi::getSuppliers($_GET['term']);
            if($suppliers)
            {
                foreach($suppliers as $supplier){
                    $id        = $supplier['id'];
                    $str       = trim($supplier['name']);
                    $results[] = array(
                        'id'    => $id,
                        'label' => $str,
                        'name'  => $str
                    );
                }
            }
        }

        echo json_encode($results);
        exit;
    }

    /**
     * 根据供应商id和sku模糊查询sku和名称用于提示信息
     * 和SKU基础资料系统对接的
     * @author zhjx
     */
    public function action_get_supplier_sku()
    {
        $re = array();
        if(isset($_GET['supplier_id']) and ($supplier_id = trim($_GET['supplier_id']))){

            $sku = isset($_GET['term'])?$_GET['term']:NULL;
            $supplier_sku = Newerpclientapi::getSupplierSkuLike($supplier_id,$sku,15);
            if($supplier_sku){
                foreach($supplier_sku as $sku){
                    $sku_tmp = strtoupper(trim($sku['sku']));
                    $re[]    = array(
                        'label' => ($sku_tmp.':'.$sku['productname']),
                        'sku'   => $sku_tmp
                    );
                }
            }
        }

        echo json_encode($re);
        exit;
    }
    /**
     *  查询sku
     *  作者:kelvin
     * */
    public function action_getSupplierFromSku()
    {
        $re = array();
        $sku = isset($_POST['sku'])?$_POST['sku']:NULL;
        $supplier_sku = DB::select('supplier_id','supplier_name')->from('vmi_supplier_skus')->where('sku','=',$sku)->execute('newerp')->as_array();
        echo json_encode($supplier_sku);
        exit;
    }
    /**
     *  查询sku
     *  作者:kelvin
     * */
    public function action_get_skuList()
    {
        $re = array();
        if(isset($_GET['supplier_id'])){
            $supplier_id = trim($_GET['supplier_id']);
        }else{
            $supplier_id = '';
        }
        $sku = isset($_GET['term'])?$_GET['term']:NULL;
        $supplier_sku = Newerpclientapi::getSupplierSkuLike($supplier_id,$sku,15);
        if($supplier_sku){
            foreach($supplier_sku as $sku){
                $sku_tmp = strtoupper(trim($sku['sku']));
                $re[]    = array(
                    'label' => ($sku_tmp.':'.$sku['productname']),
                    'sku'   => $sku_tmp
                );
            }
        }
        echo json_encode($re);
        exit;
    }
    /**
     * 通过sku和供应商获取sku详细信息,和SKU基础资料系统对接的
     * @author zhjx
     */
    public function action_getskuinfo()
    {
        $re = array();
        if($this->request->is_ajax() and isset($_POST['supplier_id']) and isset($_POST['sku']))
        {

            $supplier_sku   = Newerpclientapi::getSupplierSkuBy($_POST['supplier_id'],$_POST['sku']);
            $re['sku']      = isset($supplier_sku['sku'])?$supplier_sku['sku']:'';
            $re['sku_name'] = isset($supplier_sku['sku'])?$supplier_sku['productname']:'';

            /**
             * SKU对应的名称
             */
            $cnname = Skusystemapi::getSkuCnname($_POST['sku']);
            $sku_info = Skusystemapi::getSkuInfoByBase($_POST['sku']);
            $re['productNumber'] = isset($sku_info[0]['productNumber'])?$sku_info[0]['productNumber']:'';//商品编码
            $re['declarationName'] = isset($sku_info[0]['chineseProductName'])?$sku_info[0]['chineseProductName']:'';//报关品名
            $re['cnname'] = isset($cnname[0]['name'])?$cnname[0]['name']:'';

            $re['nuit']     = isset($supplier_sku['nuit'])?$supplier_sku['nuit']:'';
            $re['price']    = isset($supplier_sku['price'])?$supplier_sku['price']:'';
            $re['delivery'] = isset($supplier_sku['delivery'])?$supplier_sku['delivery']:0;

            /**
             * 规格信息
             */
            $re['size'] = isset($supplier_sku['size'])?$supplier_sku['size']:0;

//            $re['price']    = round($re['price'],5);
            $re['delivery'] = date("Y-m-d",strtotime(' +'.$re['delivery'].' days'));

            $place       = Skusystemapi::getSkuPlace($_POST['sku']);
            $re['place'] = isset($place)?$place[0]['place']:'';

            $sku_price       = Skusystemapi::getSkuPrice($_POST['sku']);
            $re['sku_price'] = isset($sku_price[0]['num'])?$sku_price[0]['num']:'';
//            $re['sku_price'] = round($re['sku_price'] ,5);
            $re['merchandiser'] = Skusystemapi::getSkuMerchandiser($_POST['sku']);//获取sku跟单员

            $status       = Skusystemapi::getSkuStatus($_POST['sku']);
            $re['status'] = isset($status[0]['status'])?$status[0]['status']:'';
        }

        echo json_encode($re);
        exit;
    }

    /**
     * @time20140911
     * 新的采购单创建方法了,和SKU基础资料对接
     * @author zhjx
     */
    public function action_addpurchasenew()
    {
        $re = 0;
        if($this->request->is_ajax() and isset($_POST['supplier_info']) and isset($_POST['sku_info']) and count($_POST['sku_info'])>0){
            $purchaseorder                   = new Service_purchaseadd();
            $purchaseorder_add               = $_POST['supplier_info'];
            $purchaseorder_add['createtype'] = 1;
            $purchaseorder_add_id            = $purchaseorder->add_purchaseorder($purchaseorder_add); //echo $purchaseorder_add_id;
            if($purchaseorder_add_id>0){
                foreach($_POST['sku_info'] as $purchaseorder_detail_add){
                    $purchaseorder_detail_add_id = $purchaseorder->add_purchaseorder_details($purchaseorder_detail_add);
                    if($purchaseorder_detail_add_id==0){
                        break;
                    }
                    $re = $purchaseorder_add_id;
                }
            }
        }

        echo json_encode($re);
        exit;
    }


    /**
     *新增采购单,和SKU基础资料系统对接
     * @author zhjx
     */
    public function action_indexnew()
    {
        $this->title      = __("新建采购单");
        $id               = isset($_GET['id'])?$_GET['id']:"";
        $purchaseorder_id = Service_purchaseadd::get_purchaseorder_num();

        $view = View::factory("purchase/indexnew");
        if($id){
            $view->set('id',$id);
        }
        $view->set('purchaseorder_id',++$purchaseorder_id);
        $view->set('types', Kohana::$config->load('ratetypes')->get('types'));
        //yuqing 2015年8月15日
        $view->set('stors', DB::query(Database::SELECT, 'SELECT `di_value`,`di_caption` FROM `myr_dd_item` WHERE `dd_id` = 19')
            ->execute('outland')->as_array('di_value', 'di_caption'));
        //yuqing

        //添加国内仓库 2016-02-15
        $view->set('warehouses',purchase::getWarehouse());
        $this->response->body($view);
    }

    /**
     * 通过SKU查询创建采购单,和SKU基础资料系统对接
     * @author zhjx
     * 新的界面
     */
    public function action_addsku()
    {
        $this->title    = __('新建采购单');
        $purchase_array = Service_purchaseadd::get_purchaseorder_num();
        $view           = View::factory('purchase/addsku')
            ->set('purchase_array',$purchase_array);
        $view->set('types', Kohana::$config->load('ratetypes')->get('types'));
        //yuqing 2015年8月15日
        $view->set('stors', DB::query(Database::SELECT, 'SELECT `di_value`,`di_caption` FROM `myr_dd_item` WHERE `dd_id` = 19')
            ->execute('outland')->as_array('di_value', 'di_caption'));
        //yuqing

        //添加国内仓库 2016-02-15
        //$view->set('warehouses',purchase::getWarehouse());

        $this->response->body($view);
    }

    /**
     * 模糊匹配sku信息,和SKU基础资料系统对接
     * @author zhjx
     */
    public function action_get_sku_like()
    {
        $re = array();
        if(isset($_GET['term'])){
            $sku_lists = Skusystemapi::getLikeSku($_GET['term']);
            if($sku_lists){
                foreach($sku_lists as $sku){
                    $re[] = array('label' => $sku['sku']);
                }
            }
        }
        echo json_encode($re);
        exit;
    }

    /**
     * 通过SKu查询供应商信息,和SKU基础资料系统对接
     *
     *
     * @author zhjx
     */
    public function action_get_sku_info()
    {
        $re_json = array();

        if(isset($_POST['sku']) and trim($_POST['sku'])){
            $supplier_infos = Warningtmp::get_provider_lists(trim($_POST['sku']));

            if($supplier_infos)
            {
                $supplier_view = View::factory('purchase/supplier');
                $supplier_view->set('supplier_lists',$supplier_infos);
                $re_json['supplier_view'] = $supplier_view->render();

                /**
                 * 这是默认的供应商的ID
                 */
                $re_json['supplier_dafault_id'] = isset($supplier_infos[0]['suppid'])?$supplier_infos[0]['suppid']:0;
            }
        }
        echo json_encode($re_json);
        exit;
    }

    /**
     * 通过SKu查询供应商信息,和SKU基础资料系统对接
     *
     *
     * @author zhjx
     */
    public function action_getSupplierInfoByIdAndSku()
    {
        $re_json = array();

        if(isset($_POST['sku']) and trim($_POST['sku'])){
            $supplier_infos = Warningtmp::get_provider_lists(trim($_POST['sku']));

            if($supplier_infos)
            {
                foreach($supplier_infos as $sus) {
                    if($sus['suppid'] == $_POST['su_id']) {
                        $supplier_infos = array($sus);
                        break;
                    }
                }

                $supplier_view = View::factory('purchase/supplier');
                $supplier_view->set('supplier_lists',$supplier_infos);

                $re_json['supplier_view'] = $supplier_view->render();

                /**
                 * 这是默认的供应商的ID
                 */
                $re_json['supplier_dafault_id'] = isset($_POST['su_id'])?$_POST['su_id']:0;
            }
        }
        echo json_encode($re_json);
        exit;
    }


    /**
     * 通过供应商创建采购单界面添加一行
     * @author zhjx
     */
    public function action_supplier_addrow()
    {
        $re_json = array();
        if(isset($_POST['num'])
            and $_POST['num'] > 0)
        {
            $re_json['num'] = ++$_POST['num'];
            $view = View::factory('purchase/indexadd');
            $view->set('num',$re_json['num']);
            $re_json['view'] = $view->render();
        }

        echo json_encode($re_json);exit;
    }

    /**
     * 创建采购单信息
     * @author zhjx
     */
    public function action_createpurchasenew()
    {
        $re = array('code'=>1,'msg'=>'操作失败');
        if(isset($_POST['purchaseorders']) and isset($_POST['purchaseorder_details']))
        {

            $purchase = new Service_purchaseadd();
            $purchaseorders = array();
            $purchaseorders['purchaseorder_date'] = date('Y-m-d H:i:s');
            $purchaseorders['supplier_id']  = isset($_POST['purchaseorders']['supplier_id'])?$_POST['purchaseorders']['supplier_id']:NULL;
            $purchaseorders['purchase_id']  = User::active_user()->id;
            $purchaseorders['purchaseplaner']  = $_POST['purchaseorders']['purchaseplaner'];
            $purchaseorders['remark']       = isset($_POST['purchaseorders']['remark'])?$_POST['purchaseorders']['remark']:NULL;
            $purchaseorders['transportation_expense'] = isset($_POST['purchaseorders']['transportation_expense'])?$_POST['purchaseorders']['transportation_expense']:NULL;
            $purchaseorders['createtype']   = isset($_POST['purchaseorders']['createtype'])?$_POST['purchaseorders']['createtype']:1;
            $purchaseorders['status']       = 10;
            //yuqing 是否要设置默认值？？？
            $purchaseorders['store'] = isset($_POST['purchaseorders']['store']) ? $_POST['purchaseorders']['store'] : 0;
            //yuqing

            //添加仓库  2016-02-15
            $purchaseorders['warehouseid'] = isset($_POST['purchaseorders']['store']) ? $_POST['purchaseorders']['store'] : 0;

            $purchaseorders['contact_id']   = isset($_POST['purchaseorders']['contact_id'])?$_POST['purchaseorders']['contact_id']:NULL;
            $purchaseorders['payaccountinfo_id']  = isset($_POST['purchaseorders']['payaccountinfo_id'])?$_POST['purchaseorders']['payaccountinfo_id']:NULL;
            $purchaseorders['pay_way']      = isset($_POST['purchaseorders']['pay_way'])?$_POST['purchaseorders']['pay_way']:'';
            $purchaseorders['coin']         = DB::select('coinid')->from("payaccountinfo")->where("id", '=', $purchaseorders['payaccountinfo_id'])->execute('newerp')->get('coinid',1);
            $purchaseorders['ratetype']     = isset($_POST['purchaseorders']['rateType'])?$_POST['purchaseorders']['rateType']:0;
            $purchaseorders['rate']         = isset($_POST['purchaseorders']['coinRate'])?$_POST['purchaseorders']['coinRate']:0;
            $purchaseorders['tran']         = isset($_POST['purchaseorders']['tran'])?$_POST['purchaseorders']['tran']:0;
            $purchaseorders['transportation_expense']         = isset($_POST['purchaseorders']['transportation_expense'])?$_POST['purchaseorders']['transportation_expense']:0;
            $purchaseorders['enterprise_dominant']         = isset($_POST['purchaseorders']['enterprise_dominant'])?$_POST['purchaseorders']['enterprise_dominant']:0;
            $purchaseorders['export_tax_rebate']         = empty($_POST['purchaseorders']['enterprise_dominant'])?-1:(in_array($_POST['purchaseorders']['enterprise_dominant'],array(12))?0:1);
            $poid = $purchase->add_purchaseorder($purchaseorders);
            if($poid and $_POST['purchaseorder_details'])
            {
                foreach($_POST['purchaseorder_details'] as $purchaseorder_details)
                {
                    $purchaseorder_details_tmp = array();


                    $purchaseorder_details_tmp['supplier'] = isset($purchaseorder_details['supplier'])?$purchaseorder_details['supplier']:NULL;
                    $purchaseorder_details_tmp['sku'] = isset($purchaseorder_details['sku'])?$purchaseorder_details['sku']:NULL;

                    /**
                     * 使用SKU对应的名称
                     */
                    $cnname = Skusystemapi::getSkuCnname($purchaseorder_details_tmp['sku']);
                    $purchaseorder_details_tmp['declarationName'] = isset($purchaseorder_details['declarationName'])?$purchaseorder_details['declarationName']:'';
                    $purchaseorder_details_tmp['productNumber'] = isset($purchaseorder_details['productNumber'])?$purchaseorder_details['productNumber']:'';
                    $purchaseorder_details_tmp['sku_name'] = isset($purchaseorder_details['sku_name'])?$purchaseorder_details['sku_name']:'';
//                    $purchaseorder_details_tmp['sku_name'] = isset($purchaseorder_details['sku_name'])?$purchaseorder_details['sku_name']:NULL;
                    $purchaseorder_details_tmp['storage_position'] = isset($purchaseorder_details['storage_position'])?$purchaseorder_details['storage_position']:NULL;

                    /**
                     * 记录规格
                     */
                    $supplier_sku   = Newerpclientapi::getSupplierSkuBy($purchaseorder_details_tmp['supplier'],$purchaseorder_details_tmp['sku']);
                    $purchaseorder_details_tmp['sku_standard'] = isset($supplier_sku['size'])?$supplier_sku['size']:'';
//                    $purchaseorder_details_tmp['sku_standard'] = isset($purchaseorder_details['sku_standard'])?$purchaseorder_details['sku_standard']:NULL;
                    $purchaseorder_details_tmp['quantity'] = isset($purchaseorder_details['quantity'])?$purchaseorder_details['quantity']:NULL;
                    $purchaseorder_details_tmp['single_price'] = isset($purchaseorder_details['single_price'])?$purchaseorder_details['single_price']:NULL;
//                    $purchaseorder_details_tmp['tax_rate'] = isset($purchaseorder_details['tax_rate'])?$purchaseorder_details['tax_rate']:0;
                    $purchaseorder_details_tmp['real_tax_rate'] = supplierskus::getRealTaxRate($_POST['purchaseorders']['supplier_id'],$purchaseorder_details['sku']);
                    $purchaseorder_details_tmp['remark'] = isset($purchaseorder_details['remark'])?$purchaseorder_details['remark']:NULL;
                    $purchaseorder_details_tmp['arrive_date'] = isset($purchaseorder_details['arrive_date'])?$purchaseorder_details['arrive_date']:NULL;
                    $purchaseorder_details_tmp['status'] = 10;
                    $purchaseorder_details_tmp['tax_way'] = isset($purchaseorder_details['tax_way'])?$purchaseorder_details['tax_way']:NULL;
                    $purchaseorder_details_tmp['sku_unit'] = isset($purchaseorder_details['sku_unit'])?$purchaseorder_details['sku_unit']:NULL;
                    $purchaseorder_details_tmp['details_date'] = date('Y-m-d H:i:s');
                    //  根据sku获取sku对应的所有采购员
                    $url = 'http://192.168.5.5:802/newerpapi/putUserbySku';
                    $client = new \PHPRPC_Client($url);
                    $merchandiser = $client->getinfo(json_encode(array($purchaseorder_details_tmp['sku'])),2);
                    isset($merchandiser[$purchaseorder_details_tmp['sku']]) && 
                        $merchandiser = $merchandiser[$purchaseorder_details_tmp['sku']]['nick'];
                    $purchaseorder_details_tmp['merchandiser'] = is_array($merchandiser)?'':$merchandiser;

                    //purchaseorder_details添加仓库 20160215
                    $purchaseorder_details_tmp['warehouseid'] = isset($purchaseorder_details['store']) ? $purchaseorder_details['store'] : $purchaseorders['warehouseid'];
                    list($detail,) = $purchase->add_purchaseorder_details($purchaseorder_details_tmp);
                    if($detail){
                        logs::write_log($detail,'purchaseorder_details/insert',1);
                    }else{
                        logs::write_log('','purchaseorder_details/insert',0);
                    }

                    unset($purchaseorder_details_tmp);
                }

//                checkpurchaseorder::checkSinglePurchaseOrder($poid);//加入对采购单的审核过滤

                $re['code']=2;
                $re['msg']= "操作成功";
                $re['id'] = $poid;
            }
        }

        echo json_encode($re);
        exit;
    }

    /**
     * 计算金额信息
     */
    public function action_count_money()
    {
        $re = array('quantity'=>0,
            'single_price'=>0,
            'tax_rate'=>0,
            'tax_way'=>0,
            'money'=>0);

        if(isset($_POST['money_info']) and $_POST['money_info'])
        {
            $re['quantity'] = isset($_POST['money_info']['quantity'])?$_POST['money_info']['quantity']:0;
            $re['single_price'] = isset($_POST['money_info']['single_price'])?$_POST['money_info']['single_price']:0;
            $re['tax_rate'] = isset($_POST['money_info']['tax_rate'])?$_POST['money_info']['tax_rate']:0;
            $re['tax_way'] = isset($_POST['money_info']['tax_way'])?$_POST['money_info']['tax_way']:0;

            $re['money'] = $re['quantity'] * $re['single_price'];

            /**
             * 外含税
             */
            if($re['tax_way'] == 1)
            {
                $re['money'] = $re['money'] * (1+(float)$re['tax_rate'] / 100);
            }

        }

        echo json_encode($re);exit;
    }

    //检查sku单价与基础资粮是否一致
    public function action_check_single_price()
    {
        $re = array('code'=>1);
        if(isset($_POST)&&isset($_POST['sku'])&&$_POST['sku'])
        {
            if(isset($_POST['single_price'])&&$_POST['single_price'])
            {
                $price_sql="select num from skusystem_price
                    where sku='".trim($_POST['sku'])."'
                    order by id desc
                    limit 1";
                require_once(Kohana::find_file('vendor','phprpc/phprpc_client'));
                /*$client = new PHPRPC_Client();
                $client->useService("http://192.168.5.5:802/profitapi/execute");*/
                //$price = json_decode($client->getinfo($price_sql),true);
                $price = DB::query(Database::SELECT,$price_sql)->execute('newerp')->as_array();
                if($price&&isset($price[0]['num']))
                {
                    if($price[0]['num']<$_POST['single_price'])
                    {
                        $re = array('code'=>2);
                    }
                }
            }
        }
        echo json_encode($re);
        exit;
    }

    //检查sku的状态 2清库存 4下架 5侵权/违禁 8菜鸟模型产品
    public function action_check_sku_status()
    {
        $re = array('code'=>1,'mes'=>'');
        if(isset($_POST)&&isset($_POST['sku'])&&$_POST['sku'])
        {
            $bad_status = array(2=>'清库存',4=>'下架',5=>'侵权',8=>'菜鸟模型产品',9=>'海外仓',10=>'亚马逊');
            $status_sql="select status_id,isavailable from skusystem_status_skuss
                    where sku='".trim($_POST['sku'])."'
                    and status_id in (2,4,5,8,9,10)
                    order by id desc
                    limit 1";

            require_once(Kohana::find_file('vendor','phprpc/phprpc_client'));
            /*$client = new PHPRPC_Client();
            $client->useService("http://192.168.5.5:802/profitapi/execute");*/
            //$status = json_decode($client->getinfo($status_sql),true);
            $status = DB::query(Database::SELECT,$status_sql)->execute('newerp')->as_array();
            if($status&&isset($status[0]['status_id']))
            {
                $mes = '注意：该sku状态为 ';
                $mes .= isset($bad_status[$status[0]['status_id']])?$bad_status[$status[0]['status_id']]:'';
                if(isset($status[0]['isavailable'])&&$status[0]['isavailable']==0)
                {
                    $mes .= '且该sku不可用';
                }
                $re = array('code'=>2,'mes'=>$mes);
            }
        }
        echo json_encode($re);
        exit;
    }

    //修改采购单增加sku
    public function action_add_sku()
    {
        $re_json = array();
        if (isset($_POST['num']) and $_POST['num'] >= 0) {
            $re_json['num'] = ++$_POST['num'];
            $view = View::factory('purchase/add_sku');
            $view->set('num', $re_json['num']);
            $re_json['view'] = $view->render();
        }

        echo json_encode($re_json);
        exit;
    }

    //检测重复
    public function action_check_double_sku()
    {
        $re_json = array();

        $skus = DB::select(DB::expr('upper(sku) as sku'))->from('purchaseorder_details')
            ->where('purchaseorder_id','=',$_POST['pu_id'])
            ->execute('newerp')
            ->as_array(NULL,'sku');

        if($skus)
        {
            if(!in_array(strtoupper(trim($_POST['sku'])),$skus))
            {
                $re_json['ok'] = 1;
                echo json_encode($re_json);
                exit;
            }
        }
        $re_json['ok'] = 0;

        echo json_encode($re_json);
        exit;
    }

    //检测重复
    public function action_check_have_plan()
    {
        $re_json = array('ok'=>1);
        require_once(Kohana::find_file('vendor','phprpc/phprpc_client'));
        //$server_url='http://127.0.0.1:808/commonapi/acsystem/newerpapi/putSqlResults';
        $server_url='http://192.168.5.21:701/commonapi/acsystem/newerpapi/putSqlResults';

        $client = new PHPRPC_Client();
        $client->useService($server_url);

        $sql = "select pay_status from pu_status where pu_id=".$_POST['pu_id'];

        if($datas=json_decode($client->getData($sql),true))
        {
            if($datas[0]['pay_status']>=10)
            {
                $re_json['ok'] = 0;
            }
        }

        echo json_encode($re_json);
        exit;
    }

    //添加sku到数据库
    public function action_to_add()
    {
        $pu_id = $_POST['pu_id'];
        //获取aid与仓库id
        $re = purchase::getAidAndWid($pu_id);
        $date = date('Y-m-d H:i:s');
        $pd_ids = array();
        foreach($_POST['skus'] as $sku)
        {
            $_sku = $sku;
            //采购详情中采购单id与aid关联
            $_sku['purchaseorder_id'] = $pu_id;
            //添加仓库
            $_sku['warehouseid'] = $re['warehouseid'];
            $_sku['transportation_expense'] = 0;
            $_sku['warning_quantity'] = 0;
            $_sku['details_date'] = $date;
            $_sku['status'] = 10;

            $money_in = $_sku['single_price'] * $_sku['quantity'];
            $money = $money_in;

            if($_sku['tax_way'] == 1)
            {
                $money = $money_in*(1 + $_sku['tax_rate']);
            }

            $tax_money =  ($money*1/(1 + $_sku['tax_rate']))
                *$_sku['tax_rate'];


            $_sku['money'] = $money;
            $_sku['tax_money'] = $tax_money;
            $_sku['no_tax_money'] = 	$_sku['money']  - $_sku['tax_money'] ;


            list($insert_id, $total_rows) = DB::insert('purchaseorder_details',array_keys($_sku))
                ->values($_sku)->execute('newerp');

            if($total_rows>0)
            {
                $pd_ids[] = $insert_id;
                //原有信息
                $purchaseorder_old = DB::select()->from('purchaseorders')
                    ->where('id','=',$pu_id)->execute('newerp')->current();

                $purchaseorder_detail =  DB::select()->from('purchaseorder_details')
                    ->where('id','=',$insert_id)->execute('newerp')->current();

                $purchaseorder_new = array();
                $purchaseorder_new['money'] = $purchaseorder_old['money'] + $purchaseorder_detail['money'];
                $purchaseorder_new['transportation_expense'] = $purchaseorder_old['transportation_expense']
                    + $purchaseorder_detail['transportation_expense'];

                //更新金额运费
                DB::update('purchaseorders')
                    ->set($purchaseorder_new)
                    ->where('id','=',$pu_id)
                    ->execute('newerp');

                //分摊运费
                Settle::settle_transportation_expense($pu_id,$purchaseorder_new['transportation_expense']);
            }
        }
        if($pd_ids)
        {
            $re = DB::select()->from('purchaseorder_details')
                ->where('id','in',$pd_ids)
                ->execute('newerp')
                ->as_array();

            $tax_ways = Service_warning::get_tax_ways();

            $purchase               = Config::load('purchase_status');
            $pu_status              = $purchase->purchaseorder_details; //采购明细单状态

            $view = View::factory("purchase/append_sku");
            $view->set('pds',$re)->set('tax_ways',$tax_ways)->set('pu_status',$pu_status);
            if($re)
            {
                $money_now=DB::select('money','transportation_expense')->from('purchaseorders')->where('id','=',$pu_id)->execute('newerp')->current();
                $money_all = 0;
                if($money_now)$money_all=$money_now['money']+$money_now['transportation_expense'];
                echo json_encode(array('append'=>$view->render(),'all_money'=>$money_all));
                exit;
            }
        }
        //yuqing
        checkpurchaseorder::checkSinglePurchaseOrder($pu_id);
        //yuqing
        echo json_encode(array('append'=>''));
        exit;
    }

    public function action_createPurchaseAll()
    {
        if(isset($_POST['data']) && $_POST['data']){
            $list = array();
            foreach ($_POST['data'] as $key=>$val ){
                $list[$val['supplier_id'].$val['warehouseid'].$val['enterprise_dominant']]['order']= array(
                    'supplier_id'=> $val['supplier_id'],
                    'warehouseid'=> $val['warehouseid'],
                    'enterprise_dominant'=> $val['enterprise_dominant'],
                    //默认-1无法确定退税类型 ，只有香港主体是非出口退税,其它出口退税
                    'export_tax_rebate'=> empty($val['enterprise_dominant'])?-1:(in_array($val['enterprise_dominant'],array(12))?0:1),
                    'pay_way'=> $val['pay_way_id'],
                    'status'=> 10,
                    'purchase_id'=> User::active_user()->id,
                    'purchaseplaner'=> $val['create_user'],
                    'transportation_expense'=> $val['transportation_expense'],
                    'money'=>  $list[$val['supplier_id'].$val['warehouseid']]['order']['money']+$val['money'],
                    'remark'=> '根据sku建单',
                    'purchaseorder_date'=>  date('Y-m-d H:i:s'),
                );
                $list[$val['supplier_id'].$val['warehouseid'].$val['enterprise_dominant']]['suppliers']= array(
                    'warehouseid'=> $val['warehouseid'],
                    'pay_way_id'=> $val['pay_way_id'],
                    'payaccountinfo_id'=> $val['payaccountinfo_id'],
                    'contact_id'=> $val['contact_id'],
                    'supplier_id'=> $val['supplier_id'],
                    'createtime'=> date('Y-m-d H:i:s'),
                );
                $supplier_sku   = Newerpclientapi::getSupplierSkuBy($val['supplier_id'],$val['sku']);
                $list[$val['supplier_id'].$val['warehouseid'].$val['enterprise_dominant']]['detail'][] = array(
                    'sku' => $val['sku'],
                    'item' => $val['item'],
                    'sku_name' => $val['sku_name'],
                    'warehouseid' => $val['warehouseid'],
                    'supplier' => $val['supplier_id'],
                    'single_price' => $val['single_price'],
                    'money' => $val['money'],
                    'arrive_date' => $val['arrive_date'],
                    'storage_position' => $val['storage_position'],
                    'quantity' => $val['quantity'],
                    'merchandiser' => $val['merchandiser'],
                    'details_date' => date('Y-m-d H:i:s'),
                    'real_tax_rate' => supplierskus::getRealTaxRate($val['supplier_id'],$val['sku']),
                    'tax_rate' => 0.17,
                    'status' => 10,
                    'sku_standard'=> isset($supplier_sku['size'])?$supplier_sku['size']:'',
                );
            }
        }
        $flag = '';
        foreach ($list as $k=>$v){
            list($id,) = DB::insert('purchaseorders',array_keys($v['order']))
                ->values(array_values($v['order']))
                ->execute('newerp');
            if($id){
                logs::write_log($id,'purchaseorders',1,DB::insert('purchaseorders',array_keys($v['order']))
                    ->values(array_values($v['order']))
                    ->compile('newerp'),'创建成功');
                $v['suppliers']['poid'] = $id;
                list($pu_su_id,) = DB::insert('purchasesupplier',array_keys($v['suppliers']))
                    ->values(array_values($v['suppliers']))
                    ->execute('newerp');
                if($pu_su_id){
                    logs::write_log($pu_su_id,'purchasesupplier/insert',1,DB::insert('purchasesupplier',array_keys($v['suppliers']))
                        ->values(array_values($v['suppliers']))
                        ->compile('newerp'));
                }else{
                    $flag .= '预约单关联账户创建失败 \\n';
//                    logs::write_log($pu_su_id,'purchasesupplier/insert',0);
                }
                foreach ($v['detail'] as $c=>$a){
                    $a['purchaseorder_id'] = $id;
                    list($detail_id,) = DB::insert('purchaseorder_details',array_keys($a))
                        ->values(array_values($a))
                        ->execute('newerp');
                    if($detail_id){
                        logs::write_log($detail_id,'purchaseorder_details/insert',1, DB::insert('purchaseorder_details',array_keys($a))
                            ->values(array_values($a))
                            ->compile('newerp'));
                    }else{
                        $flag .= '预约单详情创建失败 \\n';
                        logs::write_log($detail_id,'purchaseorder_details/insert',0,DB::insert('purchaseorder_details',array_keys($a))
                            ->values(array_values($a))
                            ->compile('newerp'));
                    }
                }

            }else{
                $flag .= '预约单创建失败 \\n';
                logs::write_log($id,'purchaseorders/insert',0,DB::insert('purchaseorders',array_keys($v['order']))
                    ->values(array_values($v['order']))
                    ->execute('newerp'));

            }
        }
        if($flag!=''){
            echo json_encode(array('code'=>1,'msg'=>'操作失败'));
            exit;
        }else{
            echo json_encode(array('code'=>2,'msg'=>'操作成功'));
            exit;
        }
    }
    /**
     *  根据sku，warehouseid获取储位
     *  作者:kelvin
     * */
    public function action_getPlaceForWarehouseId()
    {
        $re = array();
        if($this->request->is_ajax() and isset($_POST['warehouseid']) and isset($_POST['sku']))
        {
            $place       = Skusystemapi::getSkuPlacesForVMI($_POST['sku'],$_POST['warehouseid']);
            $re['place'] = isset($place)?$place:'';
        }
        echo json_encode($re);
        exit;
    }

}
